package one.stand.service.impl;

import com.jmp.autocofiguration.util.OssUtil2;
import com.jmp.base.PlatformApi;
import com.jmp.base.dto.*;
import com.jmp.feign.AccountFeign;
import com.jmp.feign.SmsFeign;
import com.jmp.security.grant.wx.WxLoginService;
import com.jmp.security.grant.wx.WxLoginServiceImpl;
import lombok.extern.slf4j.Slf4j;
import one.stand.advice.ResultEnum;
import one.stand.config.SecurityProperties;
import one.stand.dto.EquCheckDto;
import one.stand.dto.WechatLoginDto;
import one.stand.entity.TokenEntity;
import one.stand.enums.CompanyStateEnums;
import one.stand.enums.LoginEnum;
import one.stand.exception.LoginException;
import one.stand.mapper.CompanyMapperExt;
import one.stand.mapper.CompanyPlatformMapperServiceLoginExt;
import one.stand.model.*;
import one.stand.request.WxLoginRequest;
import one.stand.response.LoginResponse;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.CompanyEquService;
import one.stand.service.HomeService;
import one.stand.service.UserService;
import one.stand.service.user.TokenService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * @author Administrator
 */
@Service
@Slf4j
public class HomeServiceImpl implements HomeService {
    private WxLoginService wxLoginService = new WxLoginServiceImpl();
    private static final String login_img_url = "https://open.weixin.qq.com/connect/qrconnect";

    @Autowired
    private SmsFeign smsFeign;
    @Autowired
    private AccountFeign accountFeign;

    //    @Autowired
//    private WxUrlConfig wxUrlConfig;
//    @Autowired
//    private WxPcLoginConfig wxPcLoginConfig;
    @Autowired
    private CompanyEquService companyEquService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SecurityProperties securityProperties;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;

    @Autowired
    private CompanyMapperExt companyMapperExt;
    @Autowired
    private CompanyPlatformMapperServiceLoginExt companyPlatformMapperServiceLoginExt;

    @Autowired
    private UserService userService;

    @Override
    public ResultModel<LoginResponse> loginByWeixin(WxLoginRequest request) {
        return null;

//        log.info("参数接收：{}", JSON.toJSONString(request));
//
//        try {
//            LoginEnum loginEnum = LoginEnum.getByCode(request.getLoginProgramName());
//            if (null == loginEnum) {
//                return ResultModel.checkParamFail();
//            }
//            if (!LoginEnum.GZH.equals(loginEnum) && !LoginEnum.H5_LEAD.equals(loginEnum)) {
//                Company c = companyMapperExt.selectByKey(request.getCompanyKey());
//                if (c == null) {
//                    return ResultModel.fail("账号信息错误，请联系管理员");
//                }
//                if (c.getCompanyState().equals(CompanyStateEnums.PROHIBIT.getState())) {
//                    return ResultModel.fail("小程序已被禁用请联系管理员");
//                }
//            }
//
//            AccountResponse companyAccountModel = accountResponse(request.getCompanyKey(), loginEnum);
//            AssertUtil.nonNull(companyAccountModel, "未购买服务，请联系客服");
//            if(!StringUtils.isEmpty(request.getCompanyKey())){
//                AssertUtil.isTrue(request.getCompanyKey().equals(companyAccountModel.getCompanyKey()), "未购买服务，请联系客服");
//            }
//
//            WechatLoginDto wechatLoginDto = null;
//            WechatUserInfoDto userInfoDto = null;
//            if (request.getAppOauth() != null && request.getAppOauth().containsKey("openId")) {//微信第三方授权登录
//                String unionId = MapUtils.getString(request.getAppOauth(), "unionid");
//                String sessionKey = MapUtils.getString(request.getAppOauth(), "access_token");
//                String openId = MapUtils.getString(request.getAppOauth(), "openId");
//                wechatLoginDto = WechatLoginDto.builder()
//                        .openId(openId)
//                        .sessionKey(sessionKey)
//                        .unionId(unionId)
//                        .build();
//                userInfoDto = JSONObject.parseObject(JSON.toJSONString(MapUtils.getMap(request.getAppOauth(), "userInfo")), WechatUserInfoDto.class);
//                if (org.apache.commons.lang3.StringUtils.isBlank(wechatLoginDto.getUnionId()) && Objects.nonNull(userInfoDto)) {
//                    wechatLoginDto.setUnionId(userInfoDto.getUnionid());
//                }
//            } else if ((LoginEnum.GZH.equals(loginEnum) || LoginEnum.H5_LEAD.equals(loginEnum)) && StringUtils.hasText(request.getCode())) {//公众号登陆
//                wechatLoginDto = wechatService.loginBack(request.getCode(), companyAccountModel.getAppId(), companyAccountModel.getAppSecret());
//                userInfoDto = wechatService.getUserInfo(wechatLoginDto.getAccessToken(), wechatLoginDto.getOpenId());
//            } else if (StringUtils.hasText(request.getCode())) {//小程序登陆
//                wechatLoginDto = wechatService.code2accessToken(request.getCode(), companyAccountModel.getAppId(), companyAccountModel.getAppSecret());
//                if (org.apache.commons.lang3.StringUtils.isNoneBlank(request.getEncrypteData())) {
//                    userInfoDto = wechatService.getUserInfo(request.getEncrypteData(), wechatLoginDto.getSessionKey(), request.getIv());
//                }
//                if (StringUtils.isEmpty(wechatLoginDto.getUnionId()) && Objects.nonNull(userInfoDto)) {
//                    wechatLoginDto.setUnionId(userInfoDto.getUnionid());
//                }
//            } else {
//                AssertUtil.fail("登录类型不支持");
//            }
//            log.info("微信用户信息：{}", userInfoDto);
//
//            User inModel = null;
//            boolean isOneUserLogin = isOneUserLogin(companyAccountModel.getCompanyKey(), loginEnum);
//            if (isOneUserLogin) {//1号小程序登录时
//                inModel = userAdminService.getByThirdUserOpenId(wechatLoginDto.getOpenId());
//            }
//            if (Objects.isNull(inModel) && Objects.nonNull(wechatLoginDto.getUnionId())) {// 默认unionid获取用户
//                inModel = userAdminService.getByUnionid(wechatLoginDto.getUnionId());
//            }
//            if (Objects.isNull(inModel) && LoginEnum.USER.equals(loginEnum)) {
//                inModel = userAdminService.getByUserOpenId(wechatLoginDto.getOpenId());
//            }
//            final boolean isUpdateUserInfo = Objects.nonNull(inModel)
//                    && userAdminService.isVisit(inModel.getAvatarUrl())
//                    && Objects.nonNull(userInfoDto);
//            User userModel = new User();
//
//            if (inModel == null) {
//                inModel = new User();
//                if (Objects.nonNull(userInfoDto)) {
//                    inModel.setNickeName(userInfoDto.getNickName());
//                    inModel.setAvatarUrl(userInfoDto.getAvatarUrl());
//                    inModel.setGender(userInfoDto.getGender());
//                    inModel.setCity(userInfoDto.getCity());
//                    inModel.setProvince(userInfoDto.getProvince());
//                    inModel.setCountry(userInfoDto.getCountry());
//                }
//                inModel.setUnionid(wechatLoginDto.getUnionId());
//                inModel.setEnterpriseId(companyAccountModel.getCompanyId());
//                if (LoginEnum.CRM.equals(loginEnum)) {
//                    inModel.setCrmOpenId(wechatLoginDto.getOpenId());
//                } else if (LoginEnum.USER.equals(loginEnum)) {
//                    inModel.setOpenId(wechatLoginDto.getOpenId());
//                } else if (LoginEnum.GZH.equals(loginEnum)) {
//                    inModel.setGzhState(UserAdminService.GZH_STATE_GZH);
//                }
//                userAdminService.saveUser(inModel);
//            } else {
//
//                if (org.apache.commons.lang3.StringUtils.isBlank(inModel.getUnionid())
//                        && org.apache.commons.lang3.StringUtils.isNoneBlank(wechatLoginDto.getUnionId())) {
//                    userModel.setUserId(inModel.getUserId());
//                    userModel.setUnionid(wechatLoginDto.getUnionId());
//                }
//                if (org.apache.commons.lang3.StringUtils.isNoneBlank(request.getClientId())) {
//                    userModel.setUserId(inModel.getUserId());
//                    userModel.setPushCid(request.getClientId());
//                }
//                if (LoginEnum.CRM.equals(loginEnum)
//                        && UserAdminService.GZH_STATE_NORMAl != inModel.getGzhState()
//                        && UserAdminService.GZH_STATE_APP != inModel.getGzhState()) {
//                    userModel.setUserId(inModel.getUserId());
//                    userModel.setGzhState(UserAdminService.GZH_STATE_APP);
//                }
//                if (isOneUserLogin) {
//                    userModel.setUserId(inModel.getUserId());
//                    userModel.setThirdCompanyKey(request.getCompanyKey());
//                }
//                if (isUpdateUserInfo) {
//                    userModel.setUserId(inModel.getUserId());
//                    userModel.setNickeName(userInfoDto.getNickName());
//                    userModel.setAvatarUrl(userInfoDto.getAvatarUrl());
//                    userModel.setGender(userInfoDto.getGender());
//                    userModel.setCity(userInfoDto.getCity());
//                    userModel.setProvince(userInfoDto.getProvince());
//                    userModel.setCountry(userInfoDto.getCountry());
//                }
//                if (LoginEnum.CRM.equals(loginEnum) && StringUtils.isEmpty(inModel.getCrmOpenId())) {//crm登录 用户绑定
//                    userModel.setUserId(inModel.getUserId());
//                    userModel.setCrmOpenId(wechatLoginDto.getOpenId());
//                } else if (LoginEnum.USER.equals(loginEnum) && StringUtils.isEmpty(inModel.getOpenId())) {
//                    userModel.setUserId(inModel.getUserId());
//                    userModel.setOpenId(wechatLoginDto.getOpenId());
//
//                    userAdminService.deleteByOpenId(wechatLoginDto.getOpenId());
//                }
//                if (Objects.nonNull(userModel.getUserId())) {
//                    userAdminService.update(userModel);
//                }
//            }
//            inModel = userAdminService.getByUserId(inModel.getUserId());//重新获取最新User信息
//            LoginResponse loginResponse = init(inModel, request.getCompanyKey(), wechatLoginDto.getSessionKey(), loginEnum, null);
//
//            if (LoginEnum.USER.equals(loginEnum)) {
//                boolean isAuth = !userAdminService.isVisit(inModel.getAvatarUrl());
//                loginResponse.setAuth(isAuth);
//            }
//
//            log.info("response: {}", JSON.toJSONString(loginResponse));
//
//            return ResultModel.success(loginResponse);
//        } catch (OneLoginWxErrorException e) {
//            log.error(e.getMessage(), e);
//            return ResultModel.fail(ResultEnum.FAIL_LOGIN_BadPadding);
//        } catch (DuplicateKeyException e) {
//            log.error(e.getMessage(), e);
//            return ResultModel.success();
//        } catch (OneIllegalArgumentException e) {// 验证失败返回对应错误
//            log.error(e.getMessage(), e);
//            return ResultModel.fail(e.getCode(), e.getMessage());
//        } catch (Exception e) {
//            log.error(e.getMessage(), e);
//            return ResultModel.fail(ResultEnum.FAIL_LOGIN_ERROR);
//        }
    }

    @Override
    public ResultModel getPcLoginImg(String companyKey) {
        try {
            if (StringUtils.isEmpty(companyKey)) {
                return ResultModel.checkParamFail();
            }
            AccountResponse companyAccountModel = accountResponse(companyKey, LoginEnum.CRM_PC);
            if (null == companyAccountModel) {
                return ResultModel.account();
            }
            StringBuilder url = new StringBuilder(login_img_url).append("?");
            url.append("appid=").append(companyAccountModel.getAppId()).append("&");
            url.append("redirect_uri=").append(URLEncoder.encode(companyAccountModel.getRedirectUri(), "UTF-8")).append("&");
            url.append("response_type=").append("code").append("&");
            url.append("scope=").append("snsapi_login").append("&");
            url.append("state=").append(companyKey);
            log.info("二維碼地址{}", url.toString());
            return ResultModel.success(url.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultModel.error();
        }
    }

    @Override
    public ResultModel pcLoginCallBack(String code, String equCode, String state, LoginEnum loginEnum) {
        log.info("收到pc登陆回调 {}----{}----{}", code, equCode, state);
        if (StringUtils.isEmpty(code)) {
            return ResultModel.fail("code is null");
        }

        Integer companyId = null;
        Company companyModel;
        if (loginEnum.isCheckEquCode()) {
            Assert.notNull(equCode, "设备号不能为空");
            companyId = companyEquService.check(equCode, CompanyEquService.TYPE_IPAD).getCompanyId();
            Assert.notNull(companyId, "当前设备未授权，请联系软件提供商授权！\n您的设备编号：" + equCode + "\n联系电话：0579-86669669");
            companyModel = companyMapperExt.selectByPrimaryKey(companyId);
        } else {
            companyModel = companyMapperExt.selectByKey(state);
        }
        Assert.notNull(companyModel, "企业不存在");
        Assert.isTrue(CompanyStateEnums.NORMAL.getState().equals(companyModel.getCompanyState()), "企业已禁用，请联系客服");

        String companyKey = companyModel.getCompanyKey();
        AccountResponse companyAccountModel = accountResponse(companyKey, loginEnum);
        AssertUtil.nonNull(companyAccountModel, "您的小程序还未通过验证");

        WechatLoginDto wechatLoginDto = wxLoginService.loginBack(code, companyAccountModel.getAppId(), companyAccountModel.getAppSecret());
        String unionid = wechatLoginDto.getUnionId();

        User userModel = userService.getByUnionid(unionid);
        Assert.notNull(userModel, "用户不存在");
        BusinessCard cardModel = businessCardBaseService.getByUserId(userModel.getUserId());
        AssertUtil.nonNull(cardModel, "您未创建名片，没有权限登录");
        if (Objects.nonNull(companyId)) {
            AssertUtil.isTrue(companyModel.getCompanyId().equals(cardModel.getCompanyId()), ResultEnum.NO_TOURIST);
        }

        try {
            LoginResponse loginResponse = init(userModel, companyKey, null, loginEnum, null);
            return ResultModel.success(loginResponse);
        } catch (LoginException e) {
            return ResultModel.fail(e.getMessage());
        }
    }

    @Override
    public ResultModel<LoginResponse> crmPcLoginBySms(Integer companyId, String phone, String smsCode) {
        if (StringUtils.isEmpty(smsCode)
                || StringUtils.isEmpty(phone)
                || phone.length() != 11
                || companyId == null) {
            return ResultModel.checkParamFail();
        }
        if (securityProperties.isSms()) {
            ResultModel<SmsCaptchaCheckResponse> checkResult = smsFeign.captchaCheck(SmsCaptchaCheckRequest.builder()
                    .phone(phone)
                    .type(SmsCodeEnums.login_sms.getCode())
                    .captcha(smsCode)
                    .build());
            if (!checkResult.getData().isSuccess()) {
                return ResultModel.fail("验证码错误");
            }
        }

        Company companyModel = companyMapperExt.selectByPrimaryKey(companyId);
        if (null == companyModel) {
            return ResultModel.fail("企业不存在");
        }
        User userModel = userService.getByPhone(phone, companyId);
        if (null == userModel || userModel.getUserState() != 1) {
            return ResultModel.fail("用户不存在");
        }
        try {
            LoginResponse loginResponse = init(userModel, "quanjing", null, LoginEnum.CRM_PC, null);
            return ResultModel.success(loginResponse);
        } catch (LoginException e) {
            return ResultModel.fail(e.getMessage());
        }
    }

    @Override
    public ResultModel<LoginResponse> loginIpadPwd(String username, String password, LoginEnum loginEnum) {
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(username)) {
            username = org.apache.commons.lang3.StringUtils.trim(username);
        }
        if (org.apache.commons.lang3.StringUtils.isNoneBlank(password)) {
            password = org.apache.commons.lang3.StringUtils.trim(password);
        }
        Integer userId;
        String companyKey;
        if (("admin".equals(username) && "admin@1233".equals(password))
                || ("test".equals(username) && "test@quanjing".equals(password))) {
            userId = 938;
            companyKey = "quanjing";
        } else if ("wycs".equals(username) && "wycs@133".equals(password)) {
            userId = 958;
            companyKey = "huayuan";
        } else if ("wycsz".equals(username) && "wycsz@1323".equals(password)) {
            userId = 941;
            companyKey = "quanjing";
        } else {
            return ResultModel.fail("用户名或密码错误");
        }

        User userModel = userAdminService.getByUserId(userId);
        if (null == userModel || userModel.getUserState() != 1) {
            return ResultModel.fail("用户不存在");
        }
        Company companyModel = companyMapperExt.selectByKey(companyKey);
        Assert.notNull(companyModel, "企业不存在");
        Assert.isTrue(CompanyStateEnums.NORMAL.getState().equals(companyModel.getCompanyState()), "企业已禁用，请联系客服");

        try {
            LoginResponse loginResponse = init(userModel, companyKey, null, loginEnum, null);
            return ResultModel.success(loginResponse);
        } catch (LoginException e) {
            return ResultModel.fail(e.getMessage());
        }
    }

    @Override
    public String getShowRoomLoginCode(String equCode, LoginEnum loginEnum) throws UnsupportedEncodingException {
        AssertUtil.nonNull(equCode, ResultEnum.PARAM_CHECK);
        AssertUtil.nonNull(loginEnum, ResultEnum.PARAM_CHECK);
        int type = LoginEnum.SHOWROOM_ANDROID.equals(loginEnum) ? CompanyEquService.TYPE_ANDROID : CompanyEquService.TYPE_WINDOWS;
        Integer companyId = companyEquService.check(equCode, type).getCompanyId();
        AssertUtil.nonNull(companyId, "当前设备未授权，请联系软件提供商授权！\n您的设备编号：" + equCode + "\n联系电话：0579-86669669");

        Company company = companyMapperExt.selectByPrimaryKey(companyId);
        String companyKey = company.getCompanyKey();
        AccountResponse companyAccountModel = accountResponse(companyKey, LoginEnum.SHOWROOM_ANDROID);
        AssertUtil.nonNull(companyAccountModel, ResultEnum.ACCOUNT);
        StringBuilder url = new StringBuilder(login_img_url).append("?");
        url.append("appid=").append(companyAccountModel.getAppId()).append("&");
        url.append("redirect_uri=").append(URLEncoder.encode(companyAccountModel.getRedirectUri() + "?type=" + (LoginEnum.SHOWROOM_ANDROID.equals(loginEnum) ? 0 : 1) + "&tokenid=" + equCode, "UTF-8")).append("&");
        url.append("response_type=").append("code").append("&");
        url.append("scope=").append("snsapi_login").append("&");
        url.append("state=").append(companyKey);
        log.info("二維碼地址{}", url.toString());
        return url.toString();
    }

    @Override
    public LoginResponse showroomLogin(String code, String equCode, LoginEnum loginEnum) throws LoginException {
        log.info("智慧展厅扫码登录 {}----{}----{}", code, equCode, loginEnum);
        AssertUtil.nonNull(code, ResultEnum.PARAM_CHECK);
        AssertUtil.nonNull(equCode, ResultEnum.PARAM_CHECK);
        AssertUtil.nonNull(loginEnum, ResultEnum.PARAM_CHECK);

        int type = LoginEnum.SHOWROOM_ANDROID.equals(loginEnum) ? CompanyEquService.TYPE_ANDROID : CompanyEquService.TYPE_WINDOWS;
        Integer companyId = companyEquService.check(equCode, type).getCompanyId();
        Assert.notNull(companyId, "当前设备未授权，请联系软件提供商授权！\n您的设备编号：" + equCode + "\n联系电话：0579-86669669");
        Company companyModel = companyMapperExt.selectByPrimaryKey(companyId);
        Assert.notNull(companyModel, "企业不存在");
        Assert.isTrue(CompanyStateEnums.NORMAL.getState().equals(companyModel.getCompanyState()), "企业已禁用，请联系客服");

        String companyKey = companyModel.getCompanyKey();
        AccountResponse companyAccountModel = accountResponse(companyKey, loginEnum);
        AssertUtil.nonNull(companyAccountModel, "您的小程序还未通过验证");

        String unionid;
        if ("123".equals(code)) {
            unionid = "ouTD4v9h4HJ8ShnWlXNuCfAT3uow"; // todo 联调接口用
        } else {
            WechatLoginDto wechatLoginDto = wxLoginService.loginBack(code, companyAccountModel.getAppId(), companyAccountModel.getAppSecret());
            unionid = wechatLoginDto.getUnionId();
        }

        User userModel = userService.getByUnionid(unionid);
        Assert.notNull(userModel, "用户不存在");

        BusinessCard cardModel = businessCardBaseService.getByUserId(userModel.getUserId());
        AssertUtil.nonNull(cardModel, "您未创建名片，没有权限登录");
        AssertUtil.isTrue(companyId.equals(cardModel.getCompanyId()), ResultEnum.NO_TOURIST, "用户【" + cardModel.getName() + "】不是" + companyModel.getCompanyName() + "企业成员，没有权限登录");

        LoginResponse loginResponse = init(userModel, companyKey, null, loginEnum, equCode);

        //add last user
        companyEquService.updateLastUserId(equCode, type, userModel.getUserId());

        return loginResponse;
    }

    @Override
    public String getShowRoomNoLogin(String equCode, LoginEnum loginEnum) {
        log.info("智慧展厅免登录 {}----{}", equCode, loginEnum);
        AssertUtil.nonNull(equCode, ResultEnum.PARAM_CHECK);
        AssertUtil.nonNull(loginEnum, ResultEnum.PARAM_CHECK);

        Integer type = LoginEnum.SHOWROOM_ANDROID.equals(loginEnum) ? CompanyEquService.TYPE_ANDROID : CompanyEquService.TYPE_WINDOWS;
        EquCheckDto equCheckDto = companyEquService.check(equCode, type);
        if (Objects.isNull(equCheckDto.getLastUserId())) return null;
        Integer companyId = equCheckDto.getCompanyId();
        Assert.notNull(companyId, "当前设备未授权，请联系软件提供商授权！\n您的设备编号：" + equCode + "\n联系电话：0579-86669669");

        try {
            Company companyModel = companyMapperExt.selectByPrimaryKey(companyId);
            Assert.notNull(companyModel, "企业不存在");
            Assert.isTrue(CompanyStateEnums.NORMAL.getState().equals(companyModel.getCompanyState()), "企业已禁用，请联系客服");

            String companyKey = companyModel.getCompanyKey();
            AccountResponse companyAccountModel = accountResponse(companyKey, loginEnum);
            AssertUtil.nonNull(companyAccountModel, "您的小程序还未通过验证");

            User userModel = userAdminService.getByUserId(equCheckDto.getLastUserId());
            Assert.notNull(userModel, "用户不存在");

            BusinessCard cardModel = businessCardBaseService.getByUserId(userModel.getUserId());
            AssertUtil.nonNull(cardModel, "您未创建名片，没有权限登录");
            AssertUtil.isTrue(companyId.equals(cardModel.getCompanyId()), ResultEnum.NO_TOURIST, "用户【" + cardModel.getName() + "】不是" + companyModel.getCompanyName() + "企业成员，没有权限登录");

            LoginResponse loginResponse = init(userModel, companyKey, null, loginEnum, equCode);
            return loginResponse.getToken();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    private LoginResponse init(User userModel, String companyKey, String sessionKey, LoginEnum loginEnum, String equCode) throws LoginException {

        //名片
        BusinessCard cardModel = businessCardBaseService.getByUserId(userModel.getUserId());
        if (loginEnum.isCheckCard() && cardModel == null) {
            throw new LoginException("您未创建名片，没有权限登录");
        }

        TokenEntity tokenModel = new TokenEntity();
        tokenModel.setId(Long.valueOf(userModel.getUserId()));
        tokenModel.setRoleId(userModel.getRoleId());
        tokenModel.setSessionKey(sessionKey);
        tokenModel.setCompanyKey(companyKey);
        tokenModel.setLoginProgramName(loginEnum.getCode());
        tokenModel.setEquCode(equCode);
        if (cardModel != null) {
            tokenModel.setCId(cardModel.getCompanyId().longValue());
            tokenModel.setMyCardId(cardModel.getCardId());
        } else {
            if (userModel.getRoleId() != null && userModel.getRoleId() > 0) {
                tokenModel.setCId(userModel.getRoleId().longValue());
            }
        }

        if (loginEnum.isLoginSingle()) {//单点登录时清除旧的Token
            tokenService.remove(tokenModel.getId().intValue(), loginEnum);
        }
        //登录
        tokenService.save(tokenModel);

        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setUserId(Long.valueOf(userModel.getUserId()));
        loginResponse.setToken(tokenModel.getToken());
        loginResponse.setAvatarUrl(userModel.getAvatarUrl());
        loginResponse.setUserName(userModel.getNickeName());
        loginResponse.setRoleId(userModel.getRoleId());
        loginResponse.setOssUrl(OssUtil2.getWebsiteUrl());
        loginResponse.setPhone(userModel.getPhone());
        if (null != cardModel) {
            Company companyModel = companyMapperExt.selectByPrimaryKey(cardModel.getCompanyId());
            loginResponse.setCompanyName(companyModel.getCompanyName());
            loginResponse.setQjSupplyState(companyModel.getQjSupplyState());
            loginResponse.setQjAgentState(companyModel.getQjAgentState());
            loginResponse.setCardId(cardModel.getCardId());
            loginResponse.setIsAgent(0);
        } else {
            loginResponse.setCardId(0);
        }
        return loginResponse;
    }

    private AccountResponse accountResponse(String companyKey, LoginEnum loginEnum) {
        AccountCompanyKeyRequest accountCompanyKeyRequest = AccountCompanyKeyRequest.builder()
                .companyKey(companyKey)
                .loginEnum(loginEnum)
                .build();
        ResultModel<AccountResponse> accountResponseResultModel = accountFeign.getCompanyKeyDefaultIfNull(accountCompanyKeyRequest);
        AssertUtil.isTrue(accountResponseResultModel);
        return accountResponseResultModel.getData();
    }

    private boolean isOneUserLogin(String companyKey, LoginEnum loginEnum) {
        boolean isOneUserLogin = false;
        if (LoginEnum.USER.equals(loginEnum)) {
            CompanyPlatform companyPlatform = companyPlatformMapperServiceLoginExt.select(companyKey);
            isOneUserLogin = companyPlatform.getType() == PlatformApi.TYPE_ALONE;
        }
        return isOneUserLogin;
    }
}
